//用于操作硬件设备
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "device.h"
#include "main.h"
#include <unistd.h>
#include <linux/input.h> 
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>



extern int g_maxFd;


int InitDriver()
{

        //打开按键设备文件
        g_buttonfd = open(KEY_PATH, O_RDONLY);
        if(g_buttonfd==-1) 
        {         
                return FAILURE;     
        }

        //在player.c的start_play()函数中打开了播放音乐的设备文件

        //打开DS1(led)设备文件
        g_ledfd1_trigger=open(LED_DS1_TRIGGER,O_WRONLY);
        if(g_ledfd1_trigger==-1){
                return FAILURE;
        }
        g_ledfd1_brightness=open(LED_DS1_BRIGHTNESS,O_WRONLY);
        if(g_ledfd1_brightness==-1){
                return FAILURE;
        }
        write(g_ledfd1_trigger, "none", 4);  //先将触发模式设置为none         
        write(g_ledfd1_brightness, "0", 1);   //熄灭LED 
        
        //打开DS0(led)设备文件
        g_ledfd0_trigger=open(LED_DS0_TRIGGER,O_WRONLY);
        if(g_ledfd0_trigger==-1){
                return FAILURE;
        }
        g_ledfd0_brightness=open(LED_DS0_BRIGHTNESS,O_WRONLY);
        if(g_ledfd0_brightness==-1){
                return FAILURE;
        }
        write(g_ledfd0_trigger, "none", 4);  //先将触发模式设置为none         
        write(g_ledfd0_brightness, "0", 1);   //熄灭LED 
        
        return SUCCESS;
}

int get_key_id()
{
        struct input_event in_ev = {0};         
        int id=-1;

        /* 读取数据 */         
        if (sizeof(struct input_event) != read(g_buttonfd, &in_ev, sizeof(struct input_event))) 
        {             
                perror("read error");             
                exit(-1);         
        }          
        if (EV_KEY == in_ev.type)               //按键事件 
        { 
                //0松开，1按下，2长按
                if(in_ev.value==1)
                {
                        if(in_ev.code==114)     //key0
                        {
                                id=0;
                                return id;
                        }
                        else if(in_ev.code==115)     //key1
                        {
                                id=1;
                                return id;
                        }
                }                   
        
        }     
        
        return id;
}